/**
 * 用户登录相关模块的路由
 * 
 */

const express = require('express')
const md5 = require('blueimp-md5')
const User = require('../models/user')

const router = express.Router()

router.get('/', (req, res) => {
  res.render('login/login.html')
})

router.post('/', (req, res) => {
  // res.render('index.html') // 异步请求无法重定向，ajax局部刷新，不刷新页面
  const body = req.body
  body.password = md5(md5(body.password))
  User.findOne(body, (err, user, next) => {
    if (err) {
      // 查找文件出现错误
      // 给客户端发送json字符串
      return next(err)
    }

    if (!user) {
      // 查到用户已经注册
      return res.status(200).json({
        err_code: 1,
        message: 'email is not registered yet.'
      })
    }

    // 登录成功
    // 记录登录状态
    req.session.user = user
    res.status(200).json({
      err_code: 0,
      message: 'login successfully.'
    })
  })

})

router.get('/register', (req, res) => {
  res.render('login/register.html')
})

router.post('/register', (req, res) => {
  const body = req.body
  body.password = md5(md5(body.password))
  User.findOne({
    $or: [
      { nickname: body.password },
      { email: body.email }
    ]
  }, (err, user, next) => {
    if (err) {
      return next(err)
    }

    if (user) {
      // 查到已经注册过的
      return res.status(200).json({
        err_code: 1,
        message: 'email or nickname has existed.'
      })
    }

    // 注册成功
    new User(body).save((error, data) => {
      if (error) {
        return res.status(500).json({
          err_code: 500,
          message: 'Server Error.'
        })
      }
      req.session.user = data
      res.status(200).json({
        err_code: 0,
        message: 'registered successfully.'
      })
    })
  })
})

router.get('/logout', (req, res) => {
  delete req.session.user
  res.redirect('/login')
})

module.exports = router